package sunyu.controller;

import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.multipart.MultipartFile;
import sunyu.pojo.easyui.Result;
import sunyu.toolkit.core.LogKit;
import sunyu.toolkit.core.TimeKit;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 文件上传
 *
 * @author 孙宇
 */
@Controller
public class UploadController {

    private static final Logger logger = LogKit.getLogger();

    @RequestMapping("/upload")
    @ResponseBody
    public Result upload(String url, @RequestParam(value = "file", required = false) MultipartFile[] files) {
        Result r = new Result();

        if (files != null && files.length > 0) {
            String path = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath(url);
            File p = new File(path);
            if (!p.exists()) {
                p.mkdirs();
            }
            logger.debug("准备上传到：" + path);

            List l = new ArrayList<>();
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    String fileName = file.getOriginalFilename();
                    logger.debug("上传的文件名称：" + fileName);
                    fileName = TimeKit.format("yyyyMMddHHmmss", new Date()) + fileName;
                    logger.debug("准备存到服务器改名为：" + fileName);
                    File targetFile = new File(path, fileName);
                    try {
                        file.transferTo(targetFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    String fileUrl = "/" + url + "/" + fileName;
                    l.add(fileUrl);
                    logger.debug("上传到了：" + fileUrl);
                }
            }
            r.setObj(l);
        }

        r.setSuccess(true);
        r.setMsg("成功");

        return r;
    }

}
